package com.platform.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.github.binarywang.utils.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QrCodeCreateUtil {
	 /**
	* 生成包含字符串信息的二维码图片
	* @param outputStream 文件输出流路径
	* @param content 二维码携带信息
	* @param qrCodeSize 二维码图片大小
	* @param imageFormat 二维码的格式
	* @throws WriterException 
	* @throws IOException 
	*/
	public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{  
        //设置二维码纠错级别ＭＡＰ
		Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();  
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别  
		QRCodeWriter qrCodeWriter = new QRCodeWriter();  
		//创建比特矩阵(位矩阵)的QR码编码的字符串  
		BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
//		MatrixToImageWriter.writeToPath(byteMatrix, "png", new File("d:\\temp\\qrcode.jpg"));

		// 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
		int matrixWidth = byteMatrix.getWidth();  
		BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);  
		image.createGraphics();  
		Graphics2D graphics = (Graphics2D) image.getGraphics();  
		graphics.setColor(Color.WHITE);  
		graphics.fillRect(0, 0, matrixWidth, matrixWidth);  
		// 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);  
        for (int i = 0; i < matrixWidth; i++){
            for (int j = 0; j < matrixWidth; j++){
                if (byteMatrix.get(i, j)){
                    graphics.fillRect(i-100, j-100, 1, 1);  
                }
            }
        }
        return ImageIO.write(image, imageFormat, outputStream);  
	}  
	
	public static BufferedImage createQrCode(String content, int qrCodeSize) throws WriterException, IOException{  
        //设置二维码纠错级别ＭＡＰ
		Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>();  
		hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  // 矫错级别  
		hintMap.put(EncodeHintType.MARGIN, 0);
		
		QRCodeWriter qrCodeWriter = new QRCodeWriter();  
		//创建比特矩阵(位矩阵)的QR码编码的字符串  
		BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);  
		// 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
	    int width = byteMatrix.getWidth();
	    int height = byteMatrix.getHeight();
	    BufferedImage image = new BufferedImage(width, height,
	      BufferedImage.TYPE_INT_RGB);
	    for (int x = 0; x < width; x++) {
	      for (int y = 0; y < height; y++) {
	        image.setRGB(x, y, byteMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
	      }
	    }
	    return image;
//		int matrixWidth = byteMatrix.getWidth();  
//		BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);  
//		image.createGraphics();  
//		Graphics2D graphics = (Graphics2D) image.getGraphics();  
//		graphics.setColor(Color.WHITE);  
//		graphics.fillRect(0, 0, matrixWidth, matrixWidth);  
//		// 使用比特矩阵画并保存图像
//        graphics.setColor(Color.BLACK);  
//        for (int i = 0; i < matrixWidth; i++){
//            for (int j = 0; j < matrixWidth; j++){
//                if (byteMatrix.get(i, j)){
//                    graphics.fillRect(i-100, j-100, 1, 1);  
//                }
//            }
//        }
//        return image;  
	}
	   /**
	* 读二维码并输出携带的信息
	*/
	public static String readQrCode(InputStream inputStream) throws IOException{  
	    //从输入流中获取字符串信息
		BufferedImage image = ImageIO.read(inputStream);  
		//将图像转换为二进制位图源
	    LuminanceSource source = new BufferedImageLuminanceSource(image);  
	    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  
	    QRCodeReader reader = new QRCodeReader();  
	    Result result = null ;  
	    try {
	     result = reader.decode(bitmap);  
	    } catch (ReaderException e) {
	        e.printStackTrace();  
	    }
	    return result.getText();  
	}
	
/**
 * 
	 * @Title: 构造图片
	 * @Description: 生成水印并返回java.awt.image.BufferedImage
	 * @param file
	 *            源文件(图片)
	 * @param waterFile
	 *            水印文件(图片)
	 * @param x
	 *            距离右下角的X偏移量
	 * @param y
	 *            距离右下角的Y偏移量
	 * @param alpha
	 *            透明度, 选择值从0.0~1.0: 完全透明~完全不透明
	 * @return BufferedImage
	 * @throws IOException
	 */
	public static BufferedImage watermark(File file, File waterFile, int x, int y, float alpha) throws IOException {
	    // 获取底图
	    BufferedImage buffImg = ImageIO.read(file);
	    // 获取层图
	    BufferedImage waterImg = ImageIO.read(waterFile);
	    return watermark(buffImg,waterImg,x,y,alpha);
	}
	
	public static BufferedImage watermark(BufferedImage buffImg, BufferedImage waterImg, int x, int y, float alpha) throws IOException {
	    // 创建Graphics2D对象，用在底图对象上绘图
	    Graphics2D g2d = buffImg.createGraphics();
	    int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
	    int waterImgHeight = waterImg.getHeight();// 获取层图的高度
	    // 在图形和图像中实现混合和透明效果
	    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
	    // 绘制
	    g2d.drawImage(waterImg, x, y, waterImgWidth, waterImgHeight, null);
	    g2d.dispose();// 释放图形上下文使用的系统资源
	    return buffImg;
	}
	
	/**
	 * 输出水印图片
	 * 
	 * @param buffImg
	 *            图像加水印之后的BufferedImage对象
	 * @param savePath
	 *            图像加水印之后的保存路径
	 */
	private static void generateWaterFile(BufferedImage buffImg, String savePath) {
	    int temp = savePath.lastIndexOf(".") + 1;
	    try {
	        ImageIO.write(buffImg, savePath.substring(temp), new File(savePath));
	    } catch (IOException e1) {
	        e1.printStackTrace();
	    }
	}	
	
//	/**
//	* 测试代码
//	* @throws WriterException 
//	*/
//	public static void main(String[] args) throws IOException, WriterException {  
//		BufferedImage qrImage = createQrCode("http://www.alarker.com",300);
//	    generateWaterFile(qrImage,"d:\\temp\\qrcode.jpg");  
//	    // 获取底图
//	    BufferedImage buffImg = ImageIO.read(new File("d:\\temp\\pop2.jpg"));
//	    BufferedImage aimImage = watermark(buffImg,qrImage,200,200,1);
//	    generateWaterFile(aimImage,"d:\\temp\\qrcodeAim.png");  
//	}  
}
